package ua.kharkov.khpi.tarasenko.bach.web.command.user;

import java.sql.Connection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import ua.kharkov.khpi.tarasenko.bach.core.Constant;
import ua.kharkov.khpi.tarasenko.bach.core.LocalizedResourceManager;
import ua.kharkov.khpi.tarasenko.bach.core.EShopException;
import ua.kharkov.khpi.tarasenko.bach.core.db.ConnectionManager;
import ua.kharkov.khpi.tarasenko.bach.core.db.DBUtils;
import ua.kharkov.khpi.tarasenko.bach.core.item.ItemViewBean;
import ua.kharkov.khpi.tarasenko.bach.core.user.UserBean;
import ua.kharkov.khpi.tarasenko.bach.dao.core.DAOFactory;
import ua.kharkov.khpi.tarasenko.bach.dao.core.item.ItemDAO;
import ua.kharkov.khpi.tarasenko.bach.dao.core.item.ItemDTO;
import ua.kharkov.khpi.tarasenko.bach.web.command.Command;

/**
 * Command to show item's description.
 * 
 * @author oleksandr
 * 
 */
public class ShowItemDescriptionCommand extends Command {
	private static final Logger log = Logger
			.getLogger(ShowItemDescriptionCommand.class);

	private static final String ATTRUBUTE_ITEM_VIEW_BEAN = "itemViewBean";

	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws EShopException {

		String errorMessage = null;

		String itemIdString = request.getParameter(Constant.ATTRIBUTE_ITEM_ID);
		if (log.isTraceEnabled()) {
			log.trace("Got parameter from request "
					+ Constant.ATTRIBUTE_ITEM_ID + "=" + itemIdString);
		}

		String forward = Constant.PAGE_VIEW_ITEM;
		Connection conn = null;

		// Create LocalizedResourceManager to get localized error messages
		LocalizedResourceManager LRManager = getLocalizedResourceManager(request);

		if ((itemIdString == null) || (itemIdString.isEmpty())) {

			errorMessage = LRManager
					.getMessage("error_message.item_id_not_spec");
		} else {
			int itemId = Integer.valueOf(itemIdString);
			try {
				conn = ConnectionManager.getConnection();
				ItemDAO itemDAO = DAOFactory.getDAOFactory(
						DAOFactory.DAO_TYPE.MYSQL).getItemDAO(conn);

				// Get item by it's id
				ItemDTO itemDTO = itemDAO.findItemById(itemId);
				if (itemDTO == null) {
					errorMessage = LRManager
							.getMessage("error_message.item_id_not_found"
									+ itemId);
				} else {

					// Transform found item to ItemViewBean
					ItemViewBean itemViewBean = createItemViewBean(itemDTO);

					// Put ItemViewBean object request
					request.setAttribute(ATTRUBUTE_ITEM_VIEW_BEAN, itemViewBean);

					HttpSession session = request.getSession(false);
					Integer userId = null;
					if (session == null) {
						userId = -1;
					} else {
						UserBean userBean = (UserBean) session
								.getAttribute(Constant.ATTRIBUTE_USER_BEAN);
						userId = userBean.getUserId();
					}
					log.info("User with uid=" + userId
							+ " viewed item with iid=" + itemId);

					if (log.isTraceEnabled()) {
						log.trace("Set request attribute "
								+ ATTRUBUTE_ITEM_VIEW_BEAN + ":\n" + itemDTO);
					}
				}
			} catch (EShopException e) {
				DBUtils.close(conn);
				throw e;
			} finally {
				if (conn != null) {
					DBUtils.close(conn);
				}
			}
		}

		if (errorMessage != null) {
			forward = processError(request, errorMessage);
		}

		if (log.isDebugEnabled()) {
			log.debug("Forward to " + forward);
		}
		return forward;
	}

	/**
	 * Creates ItemViewBean from ItemDTO.
	 * 
	 * @param itemDTO
	 *            .
	 * @return itemViewBean.
	 */
	private ItemViewBean createItemViewBean(ItemDTO itemDTO) {
		ItemViewBean itemViewBean = new ItemViewBean();
		itemViewBean.setId(itemDTO.getId());
		itemViewBean.setCategory(itemDTO.getCategory());
		itemViewBean.setName(itemDTO.getName());
		itemViewBean.setPrice(itemDTO.getPrice());
		itemViewBean.setDescription(itemDTO.getDescription());
		int quantity = itemDTO.getQuantity();
		boolean isAvailable = false;
		if (quantity >= 1) {
			isAvailable = true;
		} else {
			isAvailable = false;
		}
		itemViewBean.setIsAvailable(isAvailable);

		return itemViewBean;
	}
}